#coding:utf-8
import smtplib,time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from common.Log import logger
import readConfig
from common import comm

EMAIL = readConfig.ReadConfig().get_section('EMAIL')
smtpServer = EMAIL.get('smtpserver')
username = EMAIL.get('username')
password = EMAIL.get('password')
sender = EMAIL.get('sender')
receiver = EMAIL.get('receiver')

class mail:

    def __init__(self):
        self.filename = comm.find_new_report('../report')


    def content(self):
        self.msg = MIMEMultipart()
        now = time.strftime('%Y-%m-%d')
        self.msg['Subject'] = Header('接口自动化测试结果:'+now)
        self.msg['From'] = Header(sender)
        self.msg['To'] = Header(receiver,'utf-8')
        self.msg.attach(MIMEText('','plain','utf-8'))
        self.msg.attach(self.att())

    def att(self):
        sendfile = open('../report/'+self.filename,'rb').read()
        attch_file = MIMEText(sendfile,'base64','utf-8')
        attch_file['Content-Type'] = 'application/octet-stream'
        attch_file['Content-Disposition'] = 'attachment;filename="%s"'%(self.filename)
        return attch_file


    def send(self):
        try:
            smtp = smtplib.SMTP_SSL(smtpServer,465)
            smtp.login(username,password)
            self.content()
            smtp.sendmail(sender,receiver,self.msg.as_string())
        except smtplib.SMTPException as e:
            logger().error('发送邮件失败',e)

if __name__ == '__main__':
    mai = mail()
    mai.send()